﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Marbles.Core.Helpers
{
    public static class DateTools
    {
        public static int FiscalPeriodFromDate(DateTime value)
        {
            int yearportion = 0;
            int monthportion = 0;
            yearportion = value.Year;
            monthportion = value.Month - 3;

            if (monthportion < 1) { monthportion = 12 + monthportion; yearportion -= 1; }

            return (yearportion * 100) + monthportion;
        }

        public static DateTime FiscalPeriodToDate(int value)
        {
            int yearportion = 0;
            int monthportion = 0;
            yearportion = value / 100;
            monthportion = (value % 100) + 3;

            if (monthportion > 12)
            {
                monthportion = monthportion - 12;
                yearportion += 1;
            }

            return new DateTime(yearportion, monthportion, 1, 0, 0, 0);
        }

        public static int FiscalQuarterFromDate(DateTime value)
        {
            int period = FiscalPeriodFromDate(value) % 100;
            int year = FiscalPeriodFromDate(value) / 100;
            int quarter = 4;
            if ((period >=1) && (period <= 3)) {quarter=1;}
            if ((period >= 4) && (period <= 6)) { quarter = 2; }
            if ((period >= 7) && (period <= 9)) { quarter = 3; }
            return quarter;
        }

       public static int FiscalYearFromDate(DateTime value)
       {
           return FiscalPeriodFromDate(value) / 100;
       }

        public static int GetWeekNumberFromDate(DateTime value)
        {
            CultureInfo ciCurr = CultureInfo.CurrentCulture;
            int weekNum = ciCurr.Calendar.GetWeekOfYear(value, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
            return weekNum;
        }

    }
}
